"use strict";
/* Controllers */
app.controller("alertRuleAddController", ['$scope', '$location', '$rootScope', '$routeParams', 'alertRuleAddService', function ($scope, $location, $rootScope, $routeParams, alertRuleAddService) {

    var vm = $scope.vm = {};
    vm.p = {};
    vm.d = {};

    vm.d.type = $routeParams.type; // 0:为ID，1：为编码
    if(vm.d.type=='code') {
        vm.p.ruleCode = $routeParams.id; // 如果ID!=0为更新
    }else {
        vm.p.id = $routeParams.id; // 如果ID!=0为更新
    }

    var errorFn = function (result) {
        alert(result);
    };

    $scope.setAlertPolicy = function () {
        var vm = $scope.vm;
        var params = {
            id: vm.p.id,
            appCode: vm.p.appCode,
            ruleCode: vm.p.ruleCode,
            ruleName: vm.p.ruleName,
            validityDays: vm.p.validityDays,
            execTime: vm.p.execTime,
            alertPolicy: vm.p.alertPolicy,
            dutyPolicy: vm.p.dutyPolicy,
            ownerEmail: vm.p.ownerEmail
        };
        var procFn = function (res) {
            if (res.success && res.data) {
                //window.location = "#/star/alertPolicy/alertPolicy_list";
                alert("执行成功！")
            } else {
                alert(res.msg);
            }
        };
        alertRuleAddService.setAlertPolicy(params, procFn, errorFn);
    };
    $scope.getAlertPolicy = function () {
        var vm = $scope.vm;
        var params = {
            id: vm.p.id,
            ruleCode: vm.p.ruleCode
        };
        var procFn = function (res) {
            if (res.success && res.data) {
                //vm.p = JSON.stringify(response.data);
                vm.p = res.data;
                vm.p.duty = dutyPolicyParser(vm.p.dutyPolicy);
            } else {
                alert(res.msg);
            }
        };
        alertRuleAddService.getAlertPolicy(params, procFn, errorFn);
    };

    //
    if(vm.p.id!=0) {
        $scope.getAlertPolicy();
    }
}]);


/* Services */
app.service('alertRuleAddService', ['ajaxService', function (ajaxService) {

    this.setAlertPolicy = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/alert_rule/setAlertPolicy.do", successFunction, errorFunction);
    };
    this.getAlertPolicy = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/alert_rule/getAlertPolicy.do", successFunction, errorFunction);
    };
}]);

function dutyPolicyParser(dutyPolicy) {
    var obj = JSON.parse(dutyPolicy);
    return {
        "resolvegroupId": obj.resolvegroupId,
        "ctiId": obj.ctiId
    };
}
